import React, { useState } from "react";
import { listAppJwt, delAppJwt, addAppJwt, updateAppJwt } from '@/api/appjwt/appJwt'
import SearchForm from "@/components/searchForm";
import { Table, Divider, Button, message, Modal, Badge } from "antd";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import AppJwtForm from "./modules/appJwtForm";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
const queryItems = [
  {
    name: 'appName',
    label: '应用名称',
    type: 'INPUT',
  },
];
//i18n
const AppJwtIndex = () => {
  useDictionary(['sys_normal_disable']);
  const [searchParams, setSearchParams] = useState({});
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [page, setPage] = React.useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      title: '应用名称',
      dataIndex: 'appName',
      ellipsis: true,
      align: 'left',
      width: '16%'
    },
    {
      title: 'ApiKey',
      dataIndex: 'appId',
      ellipsis: true,
      align: 'left',
      width: '20%'
    },
    {
      title: 'ApiSecret',
      dataIndex: 'appSecret',
      ellipsis: true,
      align: 'left',
      width: '20%'
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      align: 'center',
      width: '10%',
      render: (text) => (<Badge status={text == '0' ? 'processing' : 'error'} text={<DisplayLabel value={text} type="sys_normal_disable" />} />)
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '10%',
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>修改</a>}
            title={`修改应用鉴权`}
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            initialValues={{
              ...record
            }}
            grid={true}
          >
            <AppJwtForm />
          </ModalForm>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];
  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-appJwt-listAppJwt', page, searchParams],
    queryFn: () => {
      return listAppJwt({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...searchParams,
      }).then((res) => {
        return res?.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const handleSave = (values) => {
    if (values.id) {
      return updateAppJwt(values).then(() => {
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return addAppJwt(values).then(() => {
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }

  const deleteConfirm = (row) => {
    const dictIds = row.id || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return delAppJwt(dictIds)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  return (
    <div size="small" className="searchTableWrapper">
      <div className="searchTableHeader">应用鉴权</div>
      <SearchForm
        onSearch={(values) => setSearchParams({ ...values })}
        items={queryItems}
        buttons={<>
          <ModalForm
            trigger={<Button className="ml-2" icon={<PlusOutlined />} type="primary">新增</Button>}
            title="添加应用鉴权"
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            grid={true}
            initialValues={{
              status: '0'
            }}
          >
            <AppJwtForm />
          </ModalForm>
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />
    </div>
  );
};


export default AppJwtIndex;
